<template>
  <view class="classifyPage">
    <view class="big_top_box">
      <view class="search_box" @tap="goLink('/pages/shop/shopSearchPage')">
        <view class="left_search_box">
          <view class="search_icon">
            <image src="../../static/images/icon/icon_search.png" class="icon-32" mode=""></image>
          </view>
          <view class="search_input">请输入搜索内容</view>
        </view>
        <view class="search_btn"><button>搜索</button></view>
      </view>
      <view class="carousel_box">
        <Carousel :val="bannerObj" @swiperClick="swiperClick"></Carousel>
      </view>
    </view>

    <view class="classify_content">
      <scroll-view scroll-y scroll-with-animation class="classify_scroll_box">
        <view class="classify_list">
          <view v-for="item in classiyList" :key="item.id" @tap="chooseClassify(item)"
            :class="['classify_item',goodsParams.team_category_id==item.id?'active_itme':'']">
            {{item.name}}
          </view>
        </view>
      </scroll-view>
      <scroll-view scroll-y scroll-with-animation class="classify_goods_scroll_box" @scrolltolower="getProductList(goodsParams)">
        <view class="classify_goods_list">
          <view class="classify_goods_item" v-for="itemData in goodsList.lists" :key="itemData.id">
            <view class="goods_img" @tap="goDetails(itemData)">
              <image :src="itemData.images[0]" mode="aspectFill"></image>
              <view class="no_num" v-if="itemData.stock==0">
                <view class="no_num_text">
                  已售完
                </view>
              </view>
            </view>
            <view class="goods_right_info_box">
              <view class="goods_name">{{ itemData.name }}</view>
              <view class="goods_price">
                <span class="fn-sz-22 fn-cl-F34035">￥</span>
                <span class="fn-sz-30 fn-cl-F34035">{{ itemData.price }}</span>
              </view>
              <view class="goods_inner_bottom_box">
                <view class="goods_sale_num fn-cl-999999 fn-sz-22">
                  <span class="mar-right-4">已售</span>
                  <span>{{ itemData.sale_num }}</span>
                </view>
                <view class="goods_shoping_car_btn" @tap="addCarFunc(itemData)">
                  <image class="icon-46" src="../../static/images/icon/icon_shoping_car_big.png" mode=""></image>
                </view>
              </view>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>
    <view class="fix_shoping_car">
      <view class="shoping_car_bottom_op_box">
        <view class="shoping_car_bottom_left_box">
          <view class="shoping_car_image" @tap="openShopingCar">
            <image class="icon-100" src="../../static/images/icon/icon_shoping_car_big.png" mode=""></image>
            <view class="shoping_car_num">{{ totalGoodsNum }}</view>
          </view>
          <view class="shoping_car_total_pirce_box">
            <view class="fn-sz-24 fn-cl-666666">
              <span class="mar-right-10">合计金额:</span>
              ￥{{ totalPrice }}
            </view>
            <view class="fn-sz-24 fn-cl-666666">
              <span class="mar-right-10">商品数量:</span>
              {{ totalGoodsNum }}
            </view>
          </view>
        </view>
        <view class="go_settle" @tap="goCreateOrder">去结算(￥{{ totalPrice }})</view>
      </view>
    </view>
    <u-popup :show="limitShow" mode="center" @close="limitClose" :round="10">
      <view class="limitModel">
        <view class="limit_tags">
          每人限购一份特价商品，确认替换原有商品吗？
        </view>
        <view class="change_goods_box_list">
          <view class="change_goods_box">
            <view class="change_goods_img">
              <image :src="curGoodsBox.newGoods.img" />
            </view>
            <view class="change_goods_name">
              {{ curGoodsBox.newGoods.name }}
            </view>
            <view class="now_pirce">
              <span class="fn-sz-22 fn-cl-F34035">￥</span>
              <span class="fn-sz-30 fn-cl-F34035">{{ curGoodsBox.newGoods.price }}</span>
            </view>
          </view>
          <view class="right_arr">
            <image class="icon-40" src="../../static/images/icon/icon_right_longarr.png" />
          </view>
          <view class="change_goods_box">
            <view class="change_goods_img">
              <image :src="curGoodsBox.orgGoods.img" />
            </view>
            <view class="change_goods_name">
              {{ curGoodsBox.orgGoods.name }}
            </view>
            <view class="now_pirce">
              <span class="fn-sz-22 fn-cl-F34035">￥</span>
              <span class="fn-sz-30 fn-cl-F34035">{{ curGoodsBox.orgGoods.price }}</span>
            </view>
          </view>
        </view>
        <div class="limit_btn_box">
          <button class="white_btn" @tap="limitClose">再想想</button>
          <button class="yellow_btn" @tap="changeNow">确认替换</button>
        </div>
      </view>
    </u-popup>
    <ShopingCar ref="shopingCar"></ShopingCar>
    <!-- <buyGoodsPopup ref="buyGoodsPopup" popupType="list"></buyGoodsPopup> -->
  </view>
</template>

<script>
import {
  mapGetters,
  mapMutations
} from 'vuex';
import Com from '../../mixin/index.js';
import Carousel from '../../components/carousel/Carousel.vue';
import GoodsList from '../../components/goodsList/goodsList.vue';
import buyGoodsPopup from '../../components/buyGoodsPopup/buyGoodsPopup.vue';
import ShopingCar from '../../components/shopingCar/shopingCar.vue';
export default {
  mixins: [Com],
  components: {
    GoodsList,
    Carousel,
    ShopingCar,
    buyGoodsPopup
  },
  data () {
    return {
      bannerObj: {
        list: [],
        height: '270rpx',
        radius: '10rpx'
      },
      classiyList: [],
      goodsParams: {
        team_id: '',
        team_category_id: ''
      },
      limitShow: false,
      buyNum: 1,
      limit: '',
      curGoodsObj: {},
      curGoodsBox: {
        orgGoods: {
          id: '',
          img: '',
          name: '',
          price: ''
        },
        newGoods: {
          id: '',
          img: '',
          name: '',
          price: ''
        }
      }
    };
  },
  onLoad () {
    this.goodsParams.team_id = uni.getStorageSync('cur_address_point').id;
    this.getClassify();
  },
  onPullDownRefresh () {
    this.getClassify();
  },
  computed: {
    ...mapGetters(['totalGoodsNum', 'totalPrice'])
  },
  methods: {
    ...mapMutations(['SET_SHOPING_CAR_LIST']),
    goDetails (val) {
      uni.navigateTo({
        url: `/pages/shop/shopDetails?product_id=${val.id}`
      });
    },
    goShopDetails (id) {
      uni.navigateTo({
        url: `/pages/shop/shopDetails?product_id=${id}&addressId=${this.curAddressGetPoint.id}`
      });
    },

    chooseClassify (row) {
      this.goodsParams.team_category_id = row.id;
      this.goodsList.lists = [];
      this.goodsList.total = 1;
      this.goodsList.total_page = 0;
      this.page.page = 1;
      this.getProductList(this.goodsParams);
    },
    addCarFunc (val) {
      this.curGoodsObj = val;
      const {
        name,
        new_price,
        price,
        id,
        images,
        stock
      } = val;
      if (stock == 0) {
        this.$helper.toast('商品已售完');
        return;
      }
      let params = {
        name,
        new_price,
        price,
        id,
        images,
        num: 1
      };
      var isNewGoods = false;
      if (Number(new_price)) {
        isNewGoods = true;
        params.price = new_price;
      }
      let isHave = false;
      let shopingCarList = this.$store.state.shopingCarList.map(elem => elem);
      let goods_ids = `${params.id}-${params.num}`;
      let arr = [goods_ids];
      shopingCarList.forEach((item, index) => {
        if (item.id != params.id) {
          arr.push(`${item.id}-${item.num}`)
        }
      });

      this.$api.checkBuyLimit({
        goods: arr + ''
      }).then(async res => {
        let {
          data
        } = await this.$api.checkBuyNumLimit({
          goods: arr + ''
        });
        //没有限购的特价商品
        let curGoodsLimitObj = {};
        let curPidIdx = res.data.on_sale_product_arr.indexOf(params.id);
        if (curPidIdx != -1) {
          //当前被限制的商品的限制数量
          curGoodsLimitObj = data[curPidIdx];
          params.limit = curGoodsLimitObj.day_limit_buy - curGoodsLimitObj.buyed_num;
          params.day_limit_buy = curGoodsLimitObj.day_limit_buy;
          this.limit = params.limit;
          console.log(curGoodsLimitObj);
        } else {
          curGoodsLimitObj = data[0]
          params.limit = curGoodsLimitObj.day_limit_buy - curGoodsLimitObj.buyed_num;
          params.day_limit_buy = curGoodsLimitObj.day_limit_buy;
          this.limit = params.limit;
        }
        if (curGoodsLimitObj.buyed_num != 0 && curPidIdx != -1) {
          this.$helper.toast('特价商品每天只能购买一次');
          return;
        }
        if (res.data.check_status) {
          shopingCarList.forEach(elem => {
            if (elem.id == params.id) {
              isHave = true;
              if (isNewGoods) {
                this.$helper.toast('新人商品只能添加一个!');
              } else {
                console.log(elem.num, params.limit, 999999999)
                if (elem.num < params.limit) {
                  elem.num += params.num;
                  this.$helper.toast('已添加进购物车');
                  elem.limit = params.limit;
                  elem.day_limit_buy = params.day_limit_buy;
                } else {
                  this.$helper.toast(
                    `今日商品限购${curGoodsLimitObj.day_limit_buy}件,超过购买数量`);
                }
              }
            }
          })
          if (!isHave) {
            if (params.limit > 0) {
              shopingCarList.push(params);
              this.$helper.toast('已添加进购物车');
            } else {
              // shopingCarList.push(params);
              this.$helper.toast(
                `今日商品限购${params.day_limit_buy}件,超过购买数量`);
            }

          }
          this.SET_SHOPING_CAR_LIST(shopingCarList);
          this.buyNum = 1;
          this.buyGoodsShow = false;
          this.$emit('submitGetGoods', params);
        }
        //限购的特价商品
        else {
          let orgGoods = {
            id: '',
            img: '',
            name: '',
            price: ''
          }

          //循环证明购物车里已经有了特价商品种类
          shopingCarList.forEach(item => {
            let id_index = res.data.on_sale_product_arr.indexOf(item.id);
            if (id_index != -1) {
              orgGoods = {
                id: item.id,
                img: item.images[0],
                name: item.name,
                price: item.price,
                num: item.num,
                limit: item.limit,
                day_limit_buy: item.day_limit_buy,
              }
            }
          })
          this.curGoodsBox = {
            orgGoods,
            newGoods: {
              id: params.id,
              img: params.images[0],
              name: params.name,
              price: params.price,
              day_limit_buy: params.day_limit_buy,
              limit: params.limit,
            }
          }

          if (orgGoods.id && res.data.on_sale_product_arr.indexOf(params.id) != -1 && this
            .curGoodsBox.orgGoods.id != this.curGoodsBox.newGoods.id) {
            this.limitShow = true;
            return;
          } else {
            this.$helper.toast('特价商品超过购买限制')
          }
        }
        return;
      })
    },
    async getClassify () {
      const {
        data
      } = await this.$api.getCate();
      this.bannerObj.list = data.banner;
      this.classiyList = data.lists;
      this.chooseClassify(this.classiyList[0]);
      uni.setStorageSync('category_banner', data.category_banner);
      console.log(data, '获取信息');
      uni.stopPullDownRefresh();
    },
    swiperClick (val) {
      let clickType = this.bannerObj.list[val];
      switch (clickType.type) {
        case 'none':
          break;
        case 'team':
          this.goShopDetails(clickType.third_id);
          break;
        case 'tour':
          uni.navigateTo({
            url: `/pages/travel/travelDetails?tour_id=${clickType.third_id}`
          });
          break;
      }
    },
    openShopingCar () {
      if (this.totalGoodsNum) {
        this.$refs.shopingCar.shopingCarShow = true;
      } else {
        this.$helper.toast('购物车是空的!');
      }
    },
    goCreateOrder () {
      if (this.totalGoodsNum) {
        uni.navigateTo({
          url: `/pages/shop/goodsSubmitOrder?type=car`
        });
      } else {
        this.$helper.toast('购物车是空的!');
      }
    },
    changeNow (goods) {
      let shopingCarList = this.$store.state.shopingCarList.filter(item => item.id != this.curGoodsBox.orgGoods
        .id);
      const {
        name,
        new_price,
        price,
        id,
        images,
        stock,
        day_limit_buy,
      } = this.curGoodsObj;
      let params = {
        name,
        new_price,
        price,
        id,
        images,
        num: this.buyNum,
        day_limit_buy
      };
      if (this.limit) {
        params.limit = this.limit;
      }
      shopingCarList.push(params);
      this.SET_SHOPING_CAR_LIST(shopingCarList);
      this.$helper.toast('已添加进购物车');
      this.limitClose();
    },
    limitClose () {
      this.limitShow = false;
      this.limit = '';
      this.curGoodsBox = {
        orgGoods: {
          id: '',
          img: '',
          name: '',
          price: ''

        },
        newGoods: {
          id: '',
          img: '',
          name: '',
          price: ''

        }
      }
    }
  }
}
</script>

<style lang="scss">
.classifyPage {
  height: 100vh;
  overflow: hidden;

  .big_top_box {
    padding: 0rpx 24rpx;

    .search_box {
      height: 68rpx;
      background: #ffffff;
      border-radius: 34rpx;
      border: 2rpx solid #fed100;
      box-sizing: border-box;
      display: flex;
      justify-content: space-between;
      margin-bottom: 30rpx;

      .left_search_box {
        padding-left: 18rpx;
        display: flex;
        align-items: center;

        .search_icon {
          margin-right: 4rpx;
        }

        .search_input {
          color: #a7a7a7;
          font-size: 26rpx;
        }
      }

      .search_btn {
        button {
          width: 120rpx;
          height: 68rpx;
          background: #fed100;
          font-size: 26rpx;
          border-radius: 34rpx;
        }
      }
    }
  }

  .classify_content {
    display: flex;

    .classify_scroll_box {
      width: 200rpx;
      height: calc(100vh - 312rpx);
      flex: none;
      background-color: #f4f4f4;

      .classify_list {
        background-color: #f4f4f4;
        padding-bottom: 300rpx;

        .classify_item {
          padding: 20rpx 20rpx;
          font-size: 30rpx;
          text-align: center;
          color: #646464;
        }

        .active_itme {
          color: #313131;
          font-size: 32rpx;
          font-weight: bold;
        }
      }
    }

    .classify_goods_scroll_box {
      flex: 1;
      height: calc(100vh - 312rpx);
      padding: 20rpx;
      box-sizing: border-box;

      .classify_goods_list {
        padding-bottom: 180rpx;

        .classify_goods_item {
          display: flex;
          margin-bottom: 8rpx;

          .goods_img {
            flex: none;
            position: relative;

            image {
              width: 180rpx;
              height: 180rpx;
              border-radius: 12rpx;
            }

            .no_num {
              position: absolute;
              top: 0;
              left: 0;
              width: 180rpx;
              height: 180rpx;
              background-color: rgba(0, 0, 0, 0.2);

              .no_num_text {
                color: #fff;
                font-size: 28rpx;
                text-align: center;
                line-height: 180rpx;
              }
            }
          }

          .goods_right_info_box {
            padding-left: 12rpx;
            flex: 1;

            .goods_name {
              font-size: 24rpx;
              color: #222222;
              margin-bottom: 4rpx;
              height: 64rpx;
              overflow: hidden;
              -webkit-line-clamp: 2;
              text-overflow: ellipsis;
              display: -webkit-box;
              -webkit-box-orient: vertical;
            }

            .goods_price {
              margin-bottom: 8rpx;
            }

            .goods_inner_bottom_box {
              display: flex;
              align-items: center;
              justify-content: space-between;

              .goods_sale_num {
              }

              .goods_shoping_car_btn {
              }
            }
          }
        }
      }
    }
  }

  .fix_shoping_car {
    position: fixed;
    bottom: 0;
    width: 100vw;
    left: 0;

    .shoping_car_bottom_op_box {
      display: flex;
      align-items: center;
      justify-content: space-between;
      background-color: #fff;
      padding: 24rpx;

      .shoping_car_bottom_left_box {
        padding-left: 120rpx;
        position: relative;

        .shoping_car_image {
          position: absolute;
          left: 0;
          top: -54rpx;

          .shoping_car_num {
            position: absolute;
            right: -8rpx;
            top: -6rpx;
            background-color: #f34035;
            border-radius: 50%;
            color: #fff;
            font-size: 26rpx;
            width: 40rpx;
            text-align: center;
            line-height: 40rpx;
            height: 40rpx;
          }
        }

        .shoping_car_total_pirce_box {
        }
      }

      .go_settle {
        color: #333;
        font-weight: bold;
        font-size: 30rpx;
        padding: 15rpx 30rpx;
        background-color: #fed100;
        border-radius: 40rpx;
      }
    }
  }
  .limitModel {
    width: 500rpx;
    padding: 50rpx 50rpx;

    .limit_tags {
      text-align: center;
      margin-bottom: 40rpx;
      font-size: 26rpx;
    }

    .change_goods_box_list {
      display: flex;
      align-items: center;
      justify-content: space-between;

      .change_goods_box {
        .change_goods_img {
          image {
            width: 200rpx;
            height: 200rpx;
          }
        }

        .change_goods_name {
          font-size: 26rpx;
        }
      }

      .right_arr {
        padding-bottom: 50rpx;
      }
    }

    .limit_btn_box {
      width: 100%;
      display: flex;
      align-items: center;
      margin-top: 40rpx;

      button {
        flex: 1;
        height: 80rpx;
        line-height: 80rpx;
        font-size: 26rpx;

        &:nth-child(2n) {
          margin-left: 20rpx;
        }
      }
    }
  }
}
</style>